package com.example.satoken.login;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.satoken.config.Result;
import com.example.satoken.DO.SysUserDo;
import com.example.satoken.mapper.SysUserMapper;
import com.example.satoken.response.UserLoginResponse;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author chenhh
 * @version v1.0
 * @date 2025/5/9 16:44
 */

@RestController
public class LoginController {
    @Resource
    private SysUserMapper userMapper;

    @PostMapping("/auth/login")
    public Result login(@RequestBody UserLoginResponse userLoginResponse) {
        SysUserDo user = userMapper.selectOne(new QueryWrapper<SysUserDo>().eq("username", userLoginResponse.getUsername()));
        new BCryptPasswordEncoder().encode(userLoginResponse.getPassword());
        if (user == null || !new BCryptPasswordEncoder().matches(userLoginResponse.getPassword(), user.getPassword())) {
            return Result.error("用户名或密码错误");
        }

        // Sa-Token登录
        StpUtil.login(user.getId());
        // 获取并缓存权限信息（会触发StpInterface的实现）
        List<String> permissionList = StpUtil.getPermissionList();
        List<String> roleList = StpUtil.getRoleList();

        return Result.ok("登录成功")
                .put("token", StpUtil.getTokenValue())
                .put("permissions", permissionList)
                .put("roles", roleList);
    }
}
